package com.xinlong.shop.framework.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinlong.shop.framework.core.entity.SysFile;
import com.xinlong.shop.framework.core.mapper.SysFileMapper;
import com.xinlong.shop.framework.service.ISysFileService;
import com.xinlong.shop.framework.uploader.AliyunOSSUploader;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * <p>
 * 系统上传文件表
 服务实现类
 * </p>
 *
 * @author Sylow
 * @since 2022-11-18
 */
@Service
public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFile> implements ISysFileService {

    private final AliyunOSSUploader aliyunOSSUploader;

    public SysFileServiceImpl(AliyunOSSUploader aliyunOSSUploader) {
        this.aliyunOSSUploader = aliyunOSSUploader;
    }


    @Override
    public void update(SysFile sysFile, Integer id) {
        UpdateWrapper<SysFile> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        this.update(sysFile, updateWrapper);
    }
    @Override
    public void delete(Integer id) {
        UpdateWrapper<SysFile> deleteWrapper = new UpdateWrapper<>();
        deleteWrapper.eq("id", id);
        this.remove(deleteWrapper);
    }

    @Override
    public SysFile upload(MultipartFile file, String scene) throws IOException {
        if (StrUtil.isEmpty(scene)) {
            scene = "default";
        }
        String fileName = file.getOriginalFilename();
        // 当前日期，用来做路径
        String nowDate = DateUtil.today().replaceAll("-","");
        // uuid, 用来做文件名称
        String uuid = IdUtil.randomUUID();
        // 获取文件类型
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
        // 文件路径 {业务}/{日期}/{uuid}.{文件类型}
        String path = scene + File.separator + nowDate + File.separator + uuid + "." + fileType;
        String url = this.aliyunOSSUploader.upload( file.getInputStream(), path, fileType);

        // 数据库存一份记录  以后删除有用
        SysFile sysFile = new SysFile();
        sysFile.setFileName(fileName);
        sysFile.setFileType(fileType);
        sysFile.setFilePath(path);
        sysFile.setUrl(url);
        this.save(sysFile);
        return sysFile;
    }

    public static void main(String[] args) {
        String nowDate = DateUtil.today().replaceAll("-","");
        System.out.println(nowDate);

        String uuid = IdUtil.randomUUID();
        System.out.println(uuid);
    }

}
